package com.sfx.concurrent.demo.concurrent.AtomicTest.demo2;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-01-18
 * Time: 16:36
 */

public class AccountCAS implements Account{
    private AtomicInteger account;

    public AccountCAS(Integer balance) {
        //初始化
        this.account = new AtomicInteger(balance);
    }

    @Override
    public Integer getBalance() {
        return account.get();
    }

    @Override
    public void withDraw(Integer money) {
        while(true) {
            //获取到最新值
            int prev = account.get();
            //要修改的值
            int next = prev - money;
            /**
             * 线程1拿到的最新值与共享变量account的最新值进行比较
             * 如果是一样的返回true,不一样返回false,说明别人已经动过了,CAS失败,
             * 再次进入while循环,继续CAS
             * 核心思想 : 不断尝试,不断尝试,直到成功,保证共享变量的线程安全
             */
            if(account.compareAndSet(prev,next)) {
                break;
            }
        }
    }
    public static void main(String[] args) {
        AccountUnSafe account1 = new AccountUnSafe(10000);
        System.out.print("加锁 : ");
        Account.demo(account1);
        AccountCAS account2 = new AccountCAS(10000);
        System.out.print("无锁 : ");
        Account.demo(account2);
    }
}
